// 购物车
const cars = {
	state: {
		carsList: [],
	},
	mutations: {
		setCarList(state, params = null) {
			// 清空
			if (!params) return state.carsList = []
			// 商品和数量
			let {
				item,
				num
			} = params;
			let caritem = {
				goods_id: item._id || item.goods_id,
				numvalue: num,
				name: item.name,
				price: item.price,
				before_price: item.before_price,
				thumb: item.thumb,
				skuArr: item.skuArr || null,
				add: item.add || false
			}
			// 查看购物车中，是否有此商品
			let idx = state.carsList.findIndex(car => {
				if (car.skuArr) {
					return car.goods_id == caritem.goods_id &&
						JSON.stringify(car.skuArr.sort()) == JSON.stringify(caritem.skuArr.sort())
				} else {
					return car.goods_id == caritem.goods_id;
				}
			})
			// 没有就添加
			if (idx < 0)
				state.carsList.unshift(caritem);
			// 有就修改数量
			else {
				if (caritem.add) {
					state.carsList[idx].numvalue += caritem.numvalue;
				} else {
					state.carsList[idx].numvalue = caritem.numvalue;
				}
				if (state.carsList[idx].numvalue <= 0)
					state.carsList.splice(idx, 1);
			}

		}
	}
}

export default cars;